const cloud = require('wx-server-sdk')
const axios = require('axios')
var rp = require('request-promise');
cloud.init()
const db = cloud.database();
const ercode = db.collection('ercode');
// 云函数入口函数
exports.main = async (event, context) => {
  console.log(event)
  const ercodeObj = await ercode.where({
    scene: event.id
  }).get()
  if (ercodeObj.data.length>0){
    return ercodeObj.data[0];
  }
  try {
    const resultValue = await rp('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx59d7f2a063c2dcf9&secret=4e5278da4c117a5cec5320cd3ecac6fb')
    const token = JSON.parse(resultValue).access_token;
    console.log('------ TOKEN:', token);

    const response = await axios({
      method: 'post',
      url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit',
      responseType: 'stream',
      params: {
        access_token: token,
      },
      data: {
        page: event.page,
        width: 300,
        scene: "id=" + event.id,
      },
    });
    const uploadFile =  await cloud.uploadFile({
      cloudPath: 'xcxcodeimages/' + Date.now() + '.png',
      fileContent: response.data,
    });
    
    var data = {
      tempFilePath: uploadFile.fileID,
      scene: event.id
    }
    const updata = await  ercode.add({
      data: data
    });
    data.id = updata;
    return data;
  } catch (err) {
    console.log('>>>>>> ERROR:', err)
  }
}